<template>
  <!-- 懒加载select组件 -->
  <el-select
    :multiple="multiple"
    v-model="selected"
    v-loadmore="loadMore"
    v-input="filterData"
    :clearable="clearable"
    :filterable="filterable"
    :disabled="disabled"
    :collapseTags="collapseTags"
    :reserve-keyword="reserveKeyword"
    :default-first-option="defaultFirstOption"
    :placeholder="placeholder"
    @change="change"
    @visible-change="visibleChange"
    @remove-tag="removeTag"
    ref="lazySelect"
    v-if="!plainText"
  >
    <el-option
      v-for="(item, index) in Options"
      :key="index"
      :label="item.label"
      :value="item.value"
      :disabled="item.disabled"
    >
      <span style="float: left">{{ item.label }}</span>
    </el-option>
    <p class="tip" v-if="loading">加载中</p>
    <p class="tip" v-if="Options.length && !loading && nomore">没有更多了</p>
  </el-select>
  <div v-else>
    <!-- {{ selected }}{{optionObj}}{{ optionObj[selected] }} -->
    <span v-if="!multiple">{{ optionObj[selected] }}</span>
    <span v-else v-for="(item, index) in selected" :key="index">{{
      (index == 0 ? "" : ",") + optionObj[item]
    }}</span>
  </div>
</template>

<script>
import emitter from "element-ui/src/mixins/emitter";
import lazy from "./lazy.mixin.js";

export default {
  mixins: [emitter, lazy],
  directives: {
    loadmore: {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function() {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          // //console.log("select scroll", condition);
          if (condition) {
            binding.value();
          }
        });
      }
    },
    input: {
      bind(el, binding) {
        let inputTimeout;
        const INPUT_DOM = el.querySelector("input[type=text]");
        INPUT_DOM.addEventListener("input", function(e) {
          if (inputTimeout) clearTimeout(inputTimeout);
          inputTimeout = setTimeout(() => {
            //console.log("输入。。。", INPUT_DOM.value);
            binding.value(INPUT_DOM.value);
          }, 500);
        });
      }
    }
  },
  props: {},
  data() {
    return {
      selected: "",
      loading: true,
      nomore: false,
      page: 1,
      Options: [],
      optionObj: {}
    };
  },
  mounted() {
    // //console.log("init lazy-select");

    this.initSelect(this.quiet);
    //直接传入data，则可以不从远程获取数据
    
    // //console.log("lazy-select", this.Options);
  },
  methods: {
    removeTag($event) {
      //console.log("removeTag", $event);
      this.$emit("remove-tag", $event);
    }
  }
};
</script>

<style lang="scss" scoped>
.tip {
  font-size: 10px;
  text-align: center;
  margin: 0;
  padding: 12px 0 8px 0;
  color: #999;
}
</style>
